package com.lxinet.jeesns.modules.wechat.web.index;

import com.blade.kit.DateKit;
import com.blade.kit.http.HttpRequest;
import com.blade.kit.json.JSONArray;
import com.blade.kit.json.JSONKit;
import com.blade.kit.json.JSONObject;
import com.lxinet.jeesns.core.annotation.Clear;
import com.lxinet.jeesns.core.dto.ResponseModel;
import com.lxinet.jeesns.core.entity.Page;
import com.lxinet.jeesns.core.web.BaseController;
import com.lxinet.jeesns.modules.wechat.entity.*;
import com.lxinet.jeesns.modules.wechat.listener.WechatListener;
import com.lxinet.jeesns.modules.wechat.listener.WechatLoginListener;
import com.lxinet.jeesns.modules.wechat.service.IWechatMetaService;
import com.lxinet.jeesns.modules.wechat.service.IWechatRecordService;
import com.lxinet.jeesns.modules.wechat.service.WechatService;
import com.lxinet.jeesns.modules.wechat.utils.Constant;
import com.lxinet.jeesns.modules.wechat.utils.FileUtil;
import com.lxinet.jeesns.modules.wechat.utils.HanderName;
import com.lxinet.jeesns.utils.JedisUtil;
import com.lxinet.jeesns.utils.SerializeUtil;
import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;

import static com.lxinet.jeesns.modules.wechat.utils.FileUtil.encodeImgageToBase64;

@Controller("indexWechatController")
@RequestMapping("/wechat")
public class WechatController extends BaseController {

    private static final String INDEX_FTL_PATH = "/index/wechat/";

    //是否打开登录监听
    private static boolean isHander=false;

    private Jedis jedis= JedisUtil.getInstance().getJedis();
//
//    @Resource
//    private WechatThread wechatThread;

    @Resource
    private WechatLoginListener wechatLoginListener;

    @Resource
    private WechatListener wechatListener;

    @Resource
    private WechatService wechatService;

    @Resource
    private IWechatMetaService wechatMetaService;

    @Resource
    private IWechatRecordService wechatRecordService;


   // private WechatListener wechatListener = new WechatListener();

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @Clear
    public String homeindex(Model model) {
        model.addAttribute("headerTitle", "头部");
        return INDEX_FTL_PATH + "/index";
    }

    /**
     * 获取多个账号切换
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/getMultipleAccounts", method = RequestMethod.GET)
    @ResponseBody
    public Object getMultipleAccounts(Model model) {
        List<Account> accounts = new ArrayList<Account>();
        Account account = new Account();
        account.setUsername("lzs");
        accounts.add(account);
        return accounts;
    }

    @RequestMapping(value = "/showQrCode")
    @ResponseBody
    public void showQrCode(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        String uuid = wechatService.getUUID();
        WechatMeta wechatMeta = new WechatMeta();
        request.getSession().setAttribute("uuid",uuid);
        String url = Constant.QRCODE_URL + uuid;
        final File output = new File("temp.jpg");
        HttpRequest.post(url, true, "t", "webwx", "_", DateKit.getCurrentUnixTime()).receive(output);
        FileInputStream inputStream = new FileInputStream(output);
        byte[] data = new byte[(int) output.length()];
        int length = inputStream.read(data);
        inputStream.close();
        response.setContentType("image/png");
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
        wechatMeta.setUuid(uuid);
        jedis.set(uuid.getBytes(), SerializeUtil.serialize(wechatMeta));
        jedis.set("tempuuid",uuid);
       /* xhThread(uuid);*/

        if(!isHander) {
            wechatLoginListener.start();
            wechatListener.start();
        }
        isHander=true;

    }

    /**
     *获取当前会话uuid
     *
     * */
    @RequestMapping(value = "/getUUID")
    @ResponseBody
    public Object getUUID(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        ResponseModel responseModel = new ResponseModel(0);
        Map<String,Object> map = new HashMap<>();
        map.put("uuid",request.getSession().getAttribute("uuid"));
        responseModel.setData(map);
        return responseModel;
    }

    /**
     *获取当前会话登录信息
     *
     * */
    @RequestMapping(value = "/getWXXX")
    @ResponseBody
    public Object getWXXX(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        ResponseModel responseModel = new ResponseModel(0);
        String uuid = (String) request.getSession().getAttribute("uuid");
        WechatMeta wechatMeta = new WechatMeta();
        if(uuid!=null&&jedis.get(uuid.getBytes())!=null){
            wechatMeta =  (WechatMeta)SerializeUtil.unserialize(jedis.get(uuid.getBytes()));
        }
        responseModel.setData(wechatMeta);
        System.out.println("获取登录信息"+wechatMeta.getDlcode());
        return responseModel;
    }

    /**
     *获取所有登录的微信信息
     *
     * */
    @RequestMapping(value = "/getAllWXXX")
    @ResponseBody
    public ResponseModel getAllWXXX(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        ResponseModel responseModel = new ResponseModel(0);
        List<WechatMeta> list = wechatMetaService.getAll();
        //buildFile(list.get(0).getUser());list.get(0).getUser();
        for(int i=0;i<list.size();i++){
            WechatMeta wechatMeta=list.get(i);
            String headImgUrl= FileUtil.getBase64ByImgFile(wechatMeta.getCookie(),JSONKit.parseObject(JSONKit.toJSONString(wechatMeta.getUser())).get("HeadImgUrl").toString());
            wechatMeta.getUser().set("HeadImgUrl",headImgUrl);
            list.set(i,wechatMeta);
        }
        responseModel.setData( JSONKit.toJSONString(list));
        return responseModel;
    }


    /**
     * 根据wxuin 获取联系人列表
     * */
    @RequestMapping(value = "/getContactByWXUIN")
    @ResponseBody
    public Object getContactByWXUIN(Integer wxuin, Model model){
        ResponseModel responseModel = new ResponseModel(0);
        WechatContact wechatContact = new WechatContact();
      /*  WechatMeta wechatMeta=new WechatMeta();
        String uuid = (String) request.getSession().getAttribute("uuid");
        if(uuid!=null&&jedis.get(uuid.getBytes())!=null){
            wechatMeta =  (WechatMeta)SerializeUtil.unserialize(jedis.get(uuid.getBytes()));
        }
        wechatContact=wechatLoginListener.imgUrlTOBase64(wechatMeta,wechatContact);*/
        wechatContact.setWxuin(wxuin.toString());
        String s = jedis.get(wechatContact.getWxuin().toString());
        responseModel.setData(s);
        return responseModel;
    }
    /**
     * 执行循环
     *
    public void xhThread(String uuid){
        WechatThread wechatThread = new WechatThread(uuid,wechatMetaService);
        wechatThread.start();
        while(wechatThread.isAlive()){
            WechatListener wechatListener = new WechatListener();
            wechatListener.start(uuid,wechatService,wechatMetaService);
        }

    }*/

    /**
     *发送消息(文本)默认全部成功（待修改 比对心跳 ）
     * */
    @RequestMapping(value = "/wxSendTextMsg")
    @ResponseBody
    public Object wxSendMsg(String wxuin, String content,String to,String dialogToUserName,String dialogFromUserName) throws UnsupportedEncodingException {
        ResponseModel responseModel = new ResponseModel(0);
        WechatMeta wechatMeta = wechatMetaService.findByWXUIN(wxuin);
        if(wechatMeta!=null){
            wechatService.wxSendMsg(wechatMeta,content,to);
            WechatRecord wechatRecord = new WechatRecord();
           // wechatRecord.setFormusername(wechatMeta.getUser().getString("UserName"));
            dialogToUserName= URLDecoder.decode(dialogToUserName,"UTF-8");
            wechatRecord.setFormusername(dialogToUserName);
            //wechatRecord.setTousername(to);
            dialogFromUserName= URLDecoder.decode(dialogFromUserName,"UTF-8");
            wechatRecord.setTousername(dialogFromUserName);
            wechatRecord.setType(1);
            wechatRecord.setCreatetime(new Date());
            wechatRecord.setFlag(0);
            wechatRecord.setWxuin(wechatMeta.getWxuin());
            wechatRecord.setContent(content);
            wechatRecordService.save(wechatRecord);
            responseModel.setCode(1);
        }
        return responseModel;
    }

    /**
     * 获取最新微信入库消息
     * [{username:'xiao',total:12,rows:[{formUserName:'',toUserName:'xiao',count:10}]}]
     * */
    @RequestMapping(value = "/getAllNewMsg")
    @ResponseBody
    public Object getAllNewMsg(){
        ResponseModel responseModel = new ResponseModel(1);
        List<WechatMeta> list = wechatMetaService.getAll();
        List<NewMsg> list_msg = new ArrayList<>();
        for(int i = 0 ; i < list.size() ; i++){
            NewMsg newMsg = new NewMsg();
            String nickname = list.get(i).getUser().getString("NickName");
            newMsg.setUsername(nickname);
            newMsg.setTotal(wechatRecordService.getCount(nickname));
            List<RowMsg> List = wechatRecordService.Conditioncount(nickname);
            newMsg.setRows(List);
            list_msg.add(newMsg);
        }
        responseModel.setData(list_msg);
        return responseModel;
    }

    /**
     * 获取具体微信入库消息
     * [{username:'xiao',total:12,rows:[{formUserName:'',toUserName:'xiao',count:10}]}]
     * */
    @RequestMapping(value = "/getNewMsgDetail")
    @ResponseBody
    public Object getNewMsgDetail(@RequestParam(value = "formusername",required = true) String  formusername,@RequestParam(value = "tousername",required = true) String  tousername) throws IOException {
        ResponseModel responseModel = new ResponseModel(0);
        formusername= URLDecoder.decode(formusername,"UTF-8");
        tousername= URLDecoder.decode(tousername,"UTF-8");
        List<WechatRecord> list = wechatRecordService.findZDMsg(formusername,tousername);
        for(int i = 0;i <list.size(); i++){
            wechatRecordService.changeFlag(list.get(i).getId());
            WechatRecord wechatRecord=list.get(i);
            String content=wechatRecord.getContent();
            if(content.indexOf("@")!=-1){
                String userName=content.substring(0,content.indexOf(":"));
                String headImgUrl="'/cgi-bin/mmwebwx-bin/webwxgeticon?username="+userName+"'";
                String uuid = (String) request.getSession().getAttribute("uuid");
                WechatMeta wechatMeta = new WechatMeta();
                if(uuid!=null&&jedis.get(uuid.getBytes())!=null){
                    wechatMeta =  (WechatMeta)SerializeUtil.unserialize(jedis.get(uuid.getBytes()));
                    String tempheadImgUrl=FileUtil.getBase64ByImgFile(wechatMeta.getCookie(),headImgUrl);
                    wechatRecord.setHeadImgUrl(tempheadImgUrl);
                }
                list.set(i,wechatRecord);
            }

        }
        responseModel.setData(list);
        return responseModel;
    }

    /**
     *分页获取历史消息
     * */
    @RequestMapping(value = "/getMsgByPage")
    @ResponseBody
    public Object getMsgByPage(@RequestParam(value = "formusername",required = true) String  formusername,@RequestParam(value = "tousername",required = true) String  tousername) throws IOException {
        Page page = new Page(request);
        formusername= URLDecoder.decode(formusername,"UTF-8");
        tousername= URLDecoder.decode(tousername,"UTF-8");
        ResponseModel responseModel=wechatRecordService.findOldMsgByPage(page,formusername,tousername);
        List<WechatRecord> list =  (List)responseModel.getData();
        for(int i = 0;i <list.size(); i++){
            WechatRecord wechatRecord=list.get(i);
            String content=wechatRecord.getContent();
            if(content.indexOf("@")!=-1){
                String uuid = (String) request.getSession().getAttribute("uuid");
                if(uuid!=null&&jedis.get(uuid.getBytes())!=null){
                    WechatMeta wechatMeta =  (WechatMeta)SerializeUtil.unserialize(jedis.get(uuid.getBytes()));
                    String userName=getUserNameByName(wechatMeta,wechatRecord.getFormusername());
                    //普通头像webwxgeticon，群头像 webwxgetheadimg
                    String headImgUrl="'/cgi-bin/mmwebwx-bin/webwxgetheadimg?username="+userName+"'";
                    String tempheadImgUrl=FileUtil.getBase64ByImgFile(wechatMeta.getCookie(),headImgUrl);
                    wechatRecord.setHeadImgUrl(tempheadImgUrl);
                }
                list.set(i,wechatRecord);
            }
        }
        responseModel.setData(list);
        return responseModel;
    }

    private String getUserNameByName(WechatMeta wechatMeta,String name) {
        String nameName = "这个人物名字未知";
        String curUserName=wechatMeta.getUser().get("NickName").toString();
        curUserName=curUserName.substring(1,curUserName.length()-1);
        if(curUserName.equals(name)){
            String curNickName=wechatMeta.getUser().get("UserName").toString();
            return curNickName.substring(1,curNickName.length()-1);
        }
        String s = jedis.get(wechatMeta.getWxuin().toString());
        JSONObject webcontact =JSONKit.parseObject(jedis.get(wechatMeta.getWxuin().toString()));
        if(webcontact!=null&&webcontact.get("groupChatList")!=null) {
            JSONArray groupChatList=(JSONArray)webcontact.get("groupChatList");
            for (int i = 0, len = groupChatList.size(); i < len; i++) {
                JSONObject groupChat =groupChatList.get(i).asJSONObject();
                if (groupChat.getString("NickName").equals(name)) {
                    nameName=groupChat.getString("UserName");
                    return nameName;
                }
            }
        }
        if(webcontact!=null&&webcontact.get("contactList")!=null) {
            JSONArray contactList=(JSONArray)webcontact.get("contactList");
            for (int i = 0, len = contactList.size(); i < len; i++) {
                JSONObject contact =contactList.get(i).asJSONObject();
                if (contact.getString("NickName").equals(name)) {
                    nameName=contact.getString("UserName");
                    return nameName;
                }
            }
        }
        if(webcontact!=null&&webcontact.get("memberList")!=null) {
            JSONArray memberList=(JSONArray)webcontact.get("memberList");
            for (int i = 0, len = memberList.size(); i < len; i++) {
                JSONObject member =memberList.get(i).asJSONObject();
                if (member.getString("NickName").equals(name)) {
                    nameName=member.getString("UserName");
                    return nameName;
                }
            }
        }
        return nameName;
    }

    /**
     *创建群聊
     * */
    @RequestMapping(value = "/createChatRoom")
    @ResponseBody
    public Object createChatRoom(String wxuin, String topic, String memberCount,String memberList) throws UnsupportedEncodingException {
        ResponseModel responseModel = new ResponseModel(0);
        WechatMeta wechatMeta = wechatMetaService.findByWXUIN(wxuin);
        String [] s  = memberList.split(",");
        JSONArray jsonArray = new JSONArray();
        for(int i = 0 ; i < s.length; i++ ){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserName", s[i]);
            jsonArray.add(jsonObject);
        }
        if(wechatMeta!=null){
            wechatService.createChatRoom(wechatMeta,topic,memberCount,jsonArray);
            wechatLoginListener.getWechatContactNew(wechatMeta);
        }
        return responseModel;
    }

    /**
     *新增群聊成员
     * */
    @RequestMapping(value = "/addToChatRoom")
    @ResponseBody
    public Object addToChatRoom(String wxuin, String chatRoomName,String addMemberList) throws UnsupportedEncodingException {
        ResponseModel responseModel = new ResponseModel(0);
        WechatMeta wechatMeta = wechatMetaService.findByWXUIN(wxuin);
        String [] s  = addMemberList.split(",");
        for(int i = 0 ; i < s.length; i++ ){
            if(wechatMeta!=null){
                wechatService.addToChatRoom(wechatMeta,chatRoomName,s[i]);
                wechatLoginListener.getWechatContactNew(wechatMeta);
            }
        }

        return responseModel;
    }

    /**
     *批量获取成员
     * @param wxuin
     * @param count 成员数
     * @param  userName
     * */
    @RequestMapping(value = "/batchGetContact")
    @ResponseBody
    public Object batchGetContact(String wxuin, String count,String userName) throws UnsupportedEncodingException {
        ResponseModel responseModel = new ResponseModel(0);
        String [] s  = userName.split(",");
        WechatMeta wechatMeta = wechatMetaService.findByWXUIN(wxuin);
        JSONArray jsonArray = new JSONArray();
        for(int i = 0 ; i < s.length; i++ ){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserName", s[i]);
            jsonArray.add(jsonObject);
        }
        JSONObject res = wechatService.batchGetContact(wechatMeta,count,jsonArray);
        JSONArray tempjsonArray=(JSONArray)res.get("ContactList");
        JSONObject jsonObj=(JSONObject)tempjsonArray.get(0);
        if(jsonObj!=null){
            responseModel.setData(JSONKit.toJSONString(jsonObj.get("MemberList")));
        }
        return responseModel;
    }

    /**
     *删除群聊成员
     * */
    @RequestMapping(value = "/updateChatRoom")
    @ResponseBody
    public Object updateChatRoom(String wxuin, String chatRoomName,String username) throws UnsupportedEncodingException {
        ResponseModel responseModel = new ResponseModel(0);
        WechatMeta wechatMeta = wechatMetaService.findByWXUIN(wxuin);
        String [] s  = username.split(",");
        for(int i = 0 ; i < s.length; i++ ){
            if(wechatMeta!=null){
                wechatService.updateChatRoom(wechatMeta,chatRoomName,s[i]);
                wechatLoginListener.getWechatContactNew(wechatMeta);
            }
        }
        return responseModel;
    }


    /**
     * 上传图片
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/springUpload")
    @ResponseBody
    public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException
    {
        String base64="";
        JSONObject retJson=new JSONObject();
        long  startTime=System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            MultipartFile file=null;
            File f=null;
            while(iter.hasNext())
            {
                //一次遍历所有文件
                 file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                     f = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") +
                            file.getOriginalFilename());
                    //上传
                    //file.transferTo(f);
                    FileOutputStream os = new FileOutputStream( f );
                    InputStream in = file.getInputStream();
                    int b = 0;
                    while((b=in.read())!=-1){ //读取文件
                        os.write(b);
                    }
                    os.flush(); //关闭流
                    in.close();
                    os.close();
                }
            }
            //上传了图片，然后再发送图片
            String uuid = (String) request.getSession().getAttribute("uuid");
            String formusername = request.getParameter("formusername");
            String tousername = request.getParameter("tousername");
            if(uuid!=null&&jedis.get(uuid.getBytes())!=null) {
                WechatMeta wechatMeta = (WechatMeta) SerializeUtil.unserialize(jedis.get(uuid.getBytes()));
                 String tempformusername=getUserNameByName(wechatMeta,formusername);
                String temptousername=getUserNameByName(wechatMeta,tousername);
                JSONObject jsonObject=wechatService.upLoadImg(wechatMeta, f,temptousername,tempformusername);
                wechatService.wxSendMsgImg(wechatMeta,jsonObject.getString("MediaId"),tempformusername);
                base64=encodeImgageToBase64(f);
                String content="<img style='width:48px;height:48px;' src='"+base64+" '/>";
                //retJson.put("content",content);


                WechatRecord wr = new WechatRecord();
                wr.setFormusername(formusername);
                wr.setTousername(tousername);
                wr.setType(1);
                wr.setCreatetime(new Date());
                wr.setFlag(1);
                wr.setWxuin(wechatMeta.getWxuin());
                wr.setContent(content);
                wechatRecordService.save(wr);
            }
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return base64;
    }
}
